package com.youlin.untils;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Comparator;
import java.util.List;

public class MakeOver {

    /**
     * 叠加图片
     * @param bgImage
     * @param headImage
     * @param headBrImage
     * @param wxImage
     * @param colors 文本颜色顺序：逝者姓名，逝者生卒年月，二维码提示
     * @param y2y
     * @param names
     * @return
     */
    public static BufferedImage pressImage(BufferedImage bgImage, BufferedImage headImage, BufferedImage headBrImage,
                                           BufferedImage wxImage, Color[] colors, String y2y, List<String> names) {
        try {
            if (bgImage == null || headImage == null || headBrImage == null || wxImage == null ||
                colors == null || StringUtils.isBlank(y2y) || CollectionUtils.isEmpty(names)) return null;

            BufferedImage image = new BufferedImage(bgImage.getWidth(), bgImage.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D g = (Graphics2D) image.getGraphics();

            // 1.在画布上渲染出背景图
            g.drawImage(bgImage, 0, 0, bgImage.getWidth(), bgImage.getHeight(), null);

            // 2.在画布上渲染出主照片和边框
            int hiX = 535;
            int hiY = 445;
            int hiW = 835;
            int hiH = 1113;
            g.drawImage(headImage, hiX+6, hiY+6, hiW-12, hiH-12, null);
            g.drawImage(headBrImage, hiX, hiY, hiW, hiH, null);

            // 3.在画布上渲染出二维码图片
            int alignX = 2150;
            g.drawImage(wxImage, alignX-(347/2), 1154, 347, 321, null);

            // 4.在画布上渲染出逝者生卒年月
            int y2yFontSize = 120;
            Font font = Font.createFont(Font.TRUETYPE_FONT, MakeOver.class.getClassLoader().getResourceAsStream("font/simhei.ttf"));
            font = font.deriveFont(Font.PLAIN, y2yFontSize);
            g.setFont(font);
            g.setColor(colors[1]);
            FontMetrics fm = g.getFontMetrics(font);
            int textWidth = fm.stringWidth(y2y);
            int y2yY = 1000;
            g.drawString(y2y, alignX-(textWidth/2), y2yY);

            // 5.在画布上渲染出逝者姓名
            String nameMax = names.parallelStream().max(Comparator.comparingInt(String::length)).orElse(null);
            int fontSize;
            switch (names.size()) {
                case 1: fontSize = 301;
                    break;
                case 2: fontSize = 171;
                    break;
                default: fontSize = 111;
            }
            do {
                font = font.deriveFont(Font.PLAIN, --fontSize);
                // 计算文字长度，计算居中的x点坐标
                fm = g.getFontMetrics(font);
                textWidth = fm.stringWidth(nameMax);
            } while (textWidth > 1550);

            g.setFont(font);
            g.setColor(colors[0]);
            int[] nameYs = new int[3];
            switch (names.size()) {
                case 1: nameYs[0] = y2yY-y2yFontSize-175;
                    break;
                case 2: nameYs[0] = y2yY-y2yFontSize-75-fontSize-55;
                    nameYs[1] = y2yY-y2yFontSize-75;
                    break;
                case 3: nameYs[0] = y2yY-y2yFontSize-35-fontSize-45-fontSize-45;
                    nameYs[1] = y2yY-y2yFontSize-35-fontSize-45;
                    nameYs[2] = y2yY-y2yFontSize-35;
            }
            for (int i = 0; i < names.size(); i++) {
                String name = names.get(i);
                fm = g.getFontMetrics(font);
                textWidth = fm.stringWidth(name);
                g.drawString(name, alignX-(textWidth/2), nameYs[i]);
            }

            // 6.在画布上渲染出二维码提示
            font = font.deriveFont(Font.PLAIN, 40);
            g.setFont(font);
            g.setColor(colors[2]);
            String tips = "微信扫码进入";
            fm = g.getFontMetrics(font);
            textWidth = fm.stringWidth(tips);
            g.drawString(tips, alignX-(textWidth/2), 1550);

            g.dispose();
            return image;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 合成 gif
     * @param outputFileName
     */
    /*public static void createGIF(String outputFileName){
        try {
            GifDecoder decoder = new GifDecoder();
            decoder.read("gif/456.gif");

            // 指定Frame的文件
            AnimatedGifEncoder e = new AnimatedGifEncoder();
            OutputStream os = new FileOutputStream(outputFileName); //输出图片
            e.start(os);// 开始处理
            e.setQuality(10); //设置图片质量
            e.setRepeat(999);  //设置循环
            e.setDelay(188); // 设置延迟时间百分比 0=100=100%原速

//            e.setTransparent(new Color(0, 0, 0, 0));
//            e.setBackground(new Color(0,0,0,0));

            for (int i = 0; i < decoder.getFrameCount(); i++) {
                BufferedImage image = decoder.getFrame(i);

//                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//                ImageIO.write(image, "png", byteArrayOutputStream);
//                byte[] bytes = byteArrayOutputStream.toByteArray();
//                byte[] compressBytes = compressPicForScale(bytes, bytes.length / 1024 / 1.5);
//                getFileByBytes(compressBytes, "", i+".png");
//                image = ImageIO.read(new ByteArrayInputStream(compressBytes));
//                ImageIO.write(image, "png", new File("gif/gifs/gif"+i+".png"));
                ImageIO.write(image, "JPEG", new File("gif/gifs/png"+i+".jpg"));
                if (i % 5 == 0) e.addFrame(image);
//                BufferedImage im = pressImage(path1, image, weidth, height);

                //可以加入对图片的处理，比如缩放，压缩质量
//                if (i % 3 == 0) e.addFrame(pic(image));
//                e.addFrame(pic(image));

                if (i % 2 == 0) System.out.printf("\033[34m %s \n", i);
                else System.out.printf("\033[31m %s \n", i);
            }
            e.finish();
        } catch (Exception e) {
            System.out.println(e);
            e.printStackTrace();
        }
    }*/

    /*public static void createGIF123(){
        try {
            // 指定Frame的文件
            AnimatedGifEncoder e = new AnimatedGifEncoder();
            OutputStream os = new FileOutputStream(new File("gif/123.gif")); //输出图片
            e.start(os);// 开始处理
            e.setQuality(10); //设置图片质量
            e.setRepeat(999);  //设置循环
            e.setDelay(100); // 设置延迟时间百分比 0=100=100%原速
            for (int i = 0; i < 125; i++) {
                FileInputStream fileInputStream = new FileInputStream(new File("gif/gifs/gif" + i + ".png"));
                BufferedImage image = ImageIO.read(fileInputStream);
//                ImageIO.write(image, "png", new File("gif/jpg-png/png"+i+".png"));
                if (i % 2 == 0) e.addFrame(image);
                if (i % 2 == 0) System.out.printf("\033[34m %s \n", i);
                else System.out.printf("\033[31m %s \n", i);
            }
            e.finish();
        } catch (Exception e) {
            System.out.println(e);
            e.printStackTrace();
        }
    }*/

    /**
     * 透明背景抠图
     * @param bi
     * @return
     */
    /*public static BufferedImage pic(BufferedImage bi) {
        ImageIcon imageIcon = new ImageIcon(bi);
        BufferedImage bufferedImage = new BufferedImage(imageIcon.getIconWidth(),
                imageIcon.getIconHeight(), BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
        g2D.setColor(Color.WHITE);
        g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon.getImageObserver());
        int alpha = 0;
        for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage.getHeight(); j1++) {
            for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage.getWidth(); j2++) {
                int rgb = bufferedImage.getRGB(j2, j1);

                int R = (rgb & 0xff0000) >> 16;
                int G = (rgb & 0xff00) >> 8;
                int B = (rgb & 0xff);

                if (R < 50 && G < 20 && B < 10) {
                    rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff);
                }

                bufferedImage.setRGB(j2, j1, rgb);
            }
        }
        g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());
        return bufferedImage;
    }*/

    /**
     * 测试生产透明背景gif
     */
    /*public static void testGif () {
        AnimatedGifEncoder encoder = new AnimatedGifEncoder();
        encoder.start("gif/out.gif");
        encoder.setTransparent(Color.WHITE);
        encoder.setRepeat(0);
        encoder.setDelay(30);

        BufferedImage img = new BufferedImage(200, 200, BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D g2d = img.createGraphics();

        for (int i=0; i<100; i++) {
            g2d.setColor(Color.WHITE);
            g2d.fillRect(0, 0, 200, 200);
            g2d.setColor(Color.BLACK);
            g2d.drawOval(0, i, 100, 100);

            encoder.addFrame(img);
        }

        g2d.dispose();
        encoder.finish();
    }

    */

    /**
     * 根据指定大小压缩图片
     * @param imageBytes  源图片字节数组
     * @param desFileSize 指定图片大小，单位kb
     * @return 压缩质量后的图片字节数组
     */
    /*
    public static byte[] compressPicForScale(byte[] imageBytes, double desFileSize) {
        if (imageBytes == null || imageBytes.length <= 0 || imageBytes.length < desFileSize * 1024) {
            return imageBytes;
        }
        long srcSize = imageBytes.length;
        double accuracy = getAccuracy(srcSize / 1024);
        try {
            while (imageBytes.length > desFileSize * 1024) {
                ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
                Thumbnails.of(inputStream)
                        .scale(accuracy)
                        .outputQuality(accuracy)
                        .toOutputStream(outputStream);
                imageBytes = outputStream.toByteArray();
            }
        } catch (Exception e) {
        }
        return imageBytes;
    }

    */

    /**
     * 自动调节精度(经验数值)
     * @param size 源图片大小
     * @return 图片压缩质量比
     */
    /*
    private static double getAccuracy(long size) {
        double accuracy;
        if (size < 900) {
            accuracy = 0.85;
        } else if (size < 2047) {
            accuracy = 0.6;
        } else if (size < 3275) {
            accuracy = 0.44;
        } else {
            accuracy = 0.4;
        }
        return accuracy;
    }

    */

    /**
     * 把一个文件转化为byte字节数组
     * @param file
     * @return
     */
    /*
    private static byte[] fileConvertToByteArray(File file) {
        byte[] data = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = fis.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            data = baos.toByteArray();
            fis.close();
            baos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    */

    /**
     * 将Byte数组转换成文件
     * @param bytes
     * @param filePath
     * @param fileName
     */
    /*public static void getFileByBytes(byte[] bytes, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists()) {// 判断文件目录是否存在
                dir.mkdirs();
            }
            File file = new File(filePath + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }*/

    /**
     * 测试压缩
     */
    /*
    public static void testCompress () {
        File file = new File("gif/Beckham.png");
        byte[] bytes = fileConvertToByteArray(file);
        byte[] bytes1 = compressPicForScale(bytes, bytes.length/1024/2);
        getFileByBytes(bytes1, "", "gif/Beckham7.png");
    }*/

}
